package com.chezai.client.utils;

import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SDCardUtil {
    public static final int ONE_K = 1024;
    public static final long ONE_M = ONE_K * 1024;
    public static final long ONE_G = ONE_M * 1024;
    private static final String TERMIANL = "terminal";
    //学员照片路径
    public static String getStudentPhotoPath(){
        return getStudentPhotoPath(System.currentTimeMillis());
    }
    public static String getStudentPhotoPath(long timeStamp){
        return getPhotoDir() + "" + DateUtil.timestampStr(timeStamp,DateUtil.sf6) + ".jpg";
    }
    public static String getCoachPhotoPath(){
        return getPhotoDir() + "" + DateUtil.timestampStr(DateUtil.sf19) + ".jpg";
    }

    /**
     * 判断sd卡是否可用
     *
     * @return
     */
    public static boolean isSDCardAvailable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 大于50M返回true;
     *
     * @return
     */
    public static boolean isSDCardCanWrite() {
        return isSDCardCanWrite(50);
    }

    /**
     * 传入指定大小，可用空间小于指定大小，或sd卡不可用时，返回false
     *
     * @param minSize
     * @return
     */
    public static boolean isSDCardCanWrite(long minSize) {
        if (isSDCardAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs statfs = new StatFs(path.getPath());
            long blockSize = statfs.getBlockSize();
            long availaBlock = statfs.getAvailableBlocks();
            if (((blockSize * availaBlock) / ONE_M) > minSize) {
                return true;
            }
        }
        return false;
    }

    public static String getDownLoadRootDirPath() {
        String rootDirPath = "";
        //如果有外部tf卡
        List<String> sDCardPaths = hasExtSDCardPaths();
        if (sDCardPaths.size() > 0) {
            if (TextUtils.equals(TerminalApplication.channelModel, Const.QHYC_C103)) {
                //小鹿设备根路径
                rootDirPath = "/mnt/sdcard";
            } else {
                rootDirPath = sDCardPaths.get(0);
            }

        } else {
            rootDirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return rootDirPath + File.separator + TERMIANL + File.separator;
    }

    /**
     * @return eg. /xx/xx/terminal/
     */
    public static String getSDCardRootDirPath() {
        String rootDirPath = "";
        //如果有外部tf卡
        List<String> sDCardPaths = hasExtSDCardPaths();
        if (sDCardPaths.size() > 0) {
            if (TextUtils.equals(TerminalApplication.channelModel, Const.QHYC_C103)) {
                //小鹿设备根路径
                rootDirPath = "/mnt/sdcard";
            } else {
                rootDirPath = sDCardPaths.get(0);
            }

        } else {
            rootDirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        rootDirPath = TerminalApplication.mContext.getFilesDir().getAbsolutePath();
        return rootDirPath + File.separator + TERMIANL + File.separator;
    }


    /**
     * 判断是否有tf卡
     *
     * @return
     */
    private static List<String> hasExtSDCardPaths() {
        List<String> paths = new ArrayList<String>();
        String extFileStatus = Environment.getExternalStorageState();
        File extFile = Environment.getExternalStorageDirectory();
        if (extFileStatus.endsWith(Environment.MEDIA_UNMOUNTED)
                && extFile.exists() && extFile.isDirectory()
                && extFile.canWrite()) {
            paths.add(extFile.getAbsolutePath());
        }
        try {
            // obtain executed result of command line status of 'mount', to judge
            // whether tfCard exists by the result
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("mount");
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            int mountPathIndex = 1;
            while ((line = br.readLine()) != null) {
                // format of sdcard file system: vfat/fuse
                if ((!line.contains("fat") && !line.contains("fuse") && !line
                        .contains("storage"))
                        || line.contains("secure")
                        || line.contains("asec")
                        || line.contains("firmware")
                        || line.contains("shell")
                        || line.contains("obb")
                        || line.contains("legacy") || line.contains("data")) {
                    continue;
                }
                String[] parts = line.split(" ");
                int length = parts.length;
                if (mountPathIndex >= length) {
                    continue;
                }
                String mountPath = parts[mountPathIndex];
                if (!mountPath.contains("/") || mountPath.contains("data")
                        || mountPath.contains("Data")) {
                    continue;
                }
                File mountRoot = new File(mountPath);
                if (!mountRoot.exists() || !mountRoot.isDirectory()
                        || !mountRoot.canWrite()) {
                    continue;
                }
                boolean equalsToPrimarySD = mountPath.equals(extFile
                        .getAbsolutePath());
                if (equalsToPrimarySD) {
                    continue;
                }
                paths.add(mountPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return paths;
    }

    /**
     * 获取应用 异常日志文件路径
     *
     * @return /sdcard/ecar/file/crash/
     */
    public static String getAppCrashLogDir() {
        String path = getSDCardRootDirPath() + "crash" + File.separator;
        verifyDirExistAndMkDirs(path);
        return path;
    }

    /**
     * 获取音频文件保存目录
     *
     * @return eg. /xx/xx/voice/
     */
    public static String getVoiceDir() {
        // 自定义文件保存路径 以拍摄时间区分命名
        String dir = getSDCardRootDirPath() + "voice" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    public static String getVoiceTempDir() {
        // 自定义文件保存路径 以拍摄时间区分命名
        String dir = getVoiceDir() + "temp" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    /**
     * 图片保存文件夹
     *
     * @return eg. /xx/xx/photo/
     */
    public static String getPhotoDir() {
        // 自定义文件保存路径 以拍摄时间区分命名
        String dir = getSDCardRootDirPath() + "photo" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    /**
     * 二维码保存文件夹
     *
     * @return eg. /xx/xx/photo/
     */
    public static String getPhotoQrDir() {
        // 自定义文件保存路径 以拍摄时间区分命名
        String dir = getPhotoDir() + "qr" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    /**
     * 下载的App，或其他文件
     * 临时文件
     *
     * @return eg. /xx/xx/temp/
     */
    public static String getTempDir() {
        String dir = getSDCardRootDirPath() + "temp" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }
    /**
     * 下载的App，或其他文件
     *
     * @return eg. /xx/xx/download/
     */
    public static String getDownloadDir() {
        String dir = getDownLoadRootDirPath() + "download" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    /**
     * 下载的App，或其他文件
     * 临时文件
     *
     * @return eg. /xx/xx/temp/
     */
    public static String getLogDir() {
        String dir = getSDCardRootDirPath() + "log" + File.separator;
        verifyDirExistAndMkDirs(dir);
        return dir;
    }

    public static String getCrashHandlerDir() {
        // 用于格式化日期,作为日志文件名的一部分
        String packName = DateUtil.timestampStr2(System.currentTimeMillis());
        // 获取程序崩溃日志路径
        String filepath = getSDCardRootDirPath() + "log" + File.separator + packName + File.separator;
        verifyDirExistAndMkDirs(filepath);
        return filepath;
    }

    /**
     * 验证文件夹时候存在，如果不存在并创建
     *
     * @param dirPath
     */
    public static void verifyDirExistAndMkDirs(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public static void fileDelete(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                String todayDate = DateUtil.timestampStr2(System.currentTimeMillis());
                for (int i = 0; i < files.length; i++) {
                    try {
                        if (files[i].isFile()) {
                            File file1 = new File(files[i].getPath());
                            long lastMod = file1.lastModified();
                            String lastTime = DateUtil.timestampStr2(lastMod);
                            if (!todayDate.equals(lastTime)) {
                                file1.delete();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
